//
//  HJLoadingView.m
//  KaiChat
//
//  Created by lx on 2023/10/18.
//

#import "HJLoadingView.h"
#import <FLAnimatedImage.h>

@interface HJLoadingView()

@property (nonatomic, weak) UIView *contentView;
@property (nonatomic, assign, getter=isAnimating) BOOL animating;
@property (nonatomic, weak) UIImageView *imageView;
@property (nonatomic, assign) CGSize imageSize;


@end


@implementation HJLoadingView


- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        self.hidesWhenStopped = YES;
        self.hidden = YES;
        self.animating = NO;
        
        UIImageView *imageView = [UIImageView addToView:self];
        
        NSArray <UIImage *>*animationImages = [self readAnimationImages];
        imageView.animationImages = animationImages;
        imageView.animationDuration = 2;
        imageView.animationRepeatCount = 0;
        [imageView startAnimating];
        
        _imageView = imageView;
        
        CGFloat width = 70;
        _imageSize = CGSizeMake(width, animationImages.firstObject.size.height * width / animationImages.firstObject.size.width);
    }
    return self;
}

- (NSArray <UIImage *>*)readAnimationImages {
    
    NSData *gifData = [NSData dataWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"loading.gif" withExtension:nil]];
    CGImageSourceRef gifSource = CGImageSourceCreateWithData((__bridge CFDataRef)gifData, NULL);
    size_t frameCount = CGImageSourceGetCount(gifSource);
    NSMutableArray <UIImage *>*animationImages = [NSMutableArray array];
    
    for (size_t i = 0; i < frameCount; i++) {
        CGImageRef frameImage = CGImageSourceCreateImageAtIndex(gifSource, i, NULL);
        UIImage *uiImage = [UIImage imageWithCGImage:frameImage];
        [animationImages addObject:uiImage];
        CGImageRelease(frameImage);
    }
    
    CFRelease(gifSource);
    return animationImages;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    _imageView.frame = CGRectMake((self.tj_width - _imageSize.width) * 0.5, (self.tj_height - _imageSize.height) * 0.5, _imageSize.width, _imageSize.height);
}

- (void)startAnimating {
    
    self.hidden = NO;
    
    if (self.animating) return;
    self.animating = YES;
    
    [self.superview bringSubviewToFront:self];
    [self.imageView startAnimating];
}

- (void)stopAnimating {
    [self.imageView stopAnimating];
    self.imageView = nil;
    if (!self.animating) return;
    self.animating = NO;
    if (self.hidesWhenStopped) {
        self.hidden = YES;
    }
}

- (CGSize)intrinsicContentSize {
    return CGSizeMake(70, 70);
}


@end
